package com.stream.utils;

import com.stream.model.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * shiro 权限管理工具类
 * Created by yebaokang on 2017/5/18.
 */
public class ShiroUtils {

    public static Session getSession( ){
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static SysUserEntity getUserEntity( ){
//      return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
        Subject subject = SecurityUtils.getSubject();
        return (SysUserEntity)subject.getPrincipal();
    }

    public static long getUserId() {
        return getUserEntity().getUserId();
    }
    
    public static void setSessionAttribute(Object key, Object   value){
        getSession().setAttribute(key, value);
    }
    
    public static Object getSessionAttribute(Object key){
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new RRException("验证失效");
        }

        getSession().removeAttribute(key);
        return kaptcha.toString();
    }
}
